import React from 'react';
import {
    Button,
    ButtonGroup,
    CheckboxGroup,
    Empty,
    Form,
    Modal,
    Popconfirm,
    Select,
    SideSheet,
    Table,
    Tag,
    TextArea,
    Toast,
    Tooltip
} from '@douyinfe/semi-ui';
import bookmarkStyle from './index.less';
import {IllustrationNoContent, IllustrationNoContentDark,} from '@douyinfe/semi-illustrations';

import videoAPI from '@/api/model/video';
import categoryAPI from '@/api/model/category';
import {history} from 'umi'

const {Column} = Table;
export default class Bookmark extends React.Component<any, any> {
    private formApi: any;

    constructor(props: any) {
        super(props);
        this.state = {
            // @ts-ignore
            typeVisible: false,
            category_id: '',
            data: [],
            formData: {},
            initValues: {},
            videoTypeSelect: [],
            tableLoading: false,
            visible: false,
            isCreate: true,
            modalVisible: false,
            pagination: {
                page_size: 10,
                page_current: 1,
                total: 0,
            },
        };
        this.handlePageChange = this.handlePageChange.bind(this);
        this.typeSelect = this.typeSelect.bind(this);
        this.getVideoList = this.getVideoList.bind(this);
        this.changeSideSheet = this.changeSideSheet.bind(this);
        this.getFormApi = this.getFormApi.bind(this);
        this.editVideo = this.editVideo.bind(this);
        this.changeVideo = this.changeVideo.bind(this);
        this.changeBookmarkSelect = this.changeBookmarkSelect.bind(this);
        this.goItemDetail = this.goItemDetail.bind(this);
        this.changeTypeVisible = this.changeTypeVisible.bind(this);
    }

    componentDidMount() {
        this.typeSelect();
        this.getVideoList();
    }

    async typeSelect() {
        const res:any = await categoryAPI.CategorySelect();
        const data:any = {};
        res.data.forEach((t:any) => {
          data[t.id] = t.name;
        });
        this.setState({
            videoTypeSelectData: data,
            videoTypeSelect: res.data,
        });
    }

    async getVideoList() {
        const {category_id}: any = this.state;
        const data = {category_id};
        if (category_id == 0) delete data.category_id;
        this.setState({
            tableLoading: true,
        });
        const {pagination}: any = this.state;
        const res = await videoAPI.VideoList({...pagination, ...data});
        this.setState({
            data: res.data,
            tableLoading: false,
        });
    }

    async handlePageChange(page_current: number) {
        const {pagination}: any = this.state;
        await this.setState({
            pagination: {
                ...pagination,
                page_current,
            },
        });
        await this.getVideoList();
    }

    changeSideSheet() {
        const {visible}: any = this.state;
        this.setState({
            visible: !visible,
            isCreate: true,
        });
        const {category_id}: any = this.state;
        if (category_id !== 0 && category_id) {
            setTimeout(() => {
                const {formData}: any = this.state;
                this.formApi.setValue('category_id', category_id + '');
            });
        }
    }

    editVideo() {
        this.setState({
            visible: true,
            isCreate: false,
        });
        setTimeout(() => {
            const {formData}: any = this.state;
            this.formApi.setValue('id', formData.id);
            this.formApi.setValue('videoName', formData.videoName);
            this.formApi.setValue('describe', formData.describe);
            this.formApi.setValue('shortDescribe', formData.shortDescribe);
            this.formApi.setValue('isMovies', formData.isMovies);
            this.formApi.setValue('cover', formData.cover);
            this.formApi.setValue('sort', formData.sort);
        });
    }

    getFormApi(formApi: any) {
        this.formApi = formApi;
    }

    async submitForm(values: any) {
        const {isCreate}: any = this.state;
        let res: any = {};
        if (isCreate) {
            res = await videoAPI.addVideo(values);
        } else {
            res = await videoAPI.editVideo(values);
        }
        if (res.status) {
            Toast.success({
                content: `${isCreate ? '创建' : '修改'}视频成功！`,
                duration: 3,
            });
            await this.changeSideSheet();
            await this.getVideoList();
        } else {
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    async delVideo() {
        const {formData}: any = this.state;
        const res: any = await videoAPI.deleteVideo({id: formData.id});
        if (res.status) {
            Toast.success({
                content: '删除视频成功',
                duration: 3,
            });
            setTimeout(() => {
                this.getVideoList();

            }, 100)
        } else {
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    changeVideo() {
        const {modalVisible}: any = this.state;
        this.setState({
            modalVisible: !modalVisible,
        });
    }

    changeTypeVisible() {
        const {typeVisible}: any = this.state;
        this.setState({
            typeVisible: !typeVisible,
        });
    }

    async changeBookmarkSelect(category_id: any) {
        await this.setState({
            category_id,
        });
        await this.getVideoList();
    }

    // 跳转子集
    goItemDetail() {
        setTimeout(() => {
            const {formData}: any = this.state
            window.sessionStorage.setItem('videoId', formData.id)
            history.push({
                pathname: '/admin/video-item',
                search: `?id=${formData.id}`
            })
        })
    }

    render() {
        const {
            data,
            pagination,
            tableLoading,
            videoTypeSelect,
            visible,
            isCreate,
            initValues,
            modalVisible,
            formData,
            typeVisible,
            videoTypeSelectData
        }: any = this.state;
        const emptyStyle = {
            padding: 30,
        };
        return (
            <div
                className={[bookmarkStyle.bookmark_container, 'content_container'].join(
                    ' ',
                )}
            >
                <div style={{display: 'flex', alignItems: 'center'}}>
                    <Button
                        style={{marginBottom: '1rem'}}
                        theme="light"
                        type="secondary"
                        onClick={this.changeSideSheet}
                    >
                        添加视频
                    </Button>
                    <Select
                        placeholder="视频分类"
                        showClear
                        style={{width: 180, marginBottom: '1rem', marginLeft: '1rem'}}
                        onChange={(e: any) => this.changeBookmarkSelect(e)}
                    >
                        {videoTypeSelect.map((t:any) => (
                            <Select.Option key={t.id} value={t.id}>
                                {t.name}
                            </Select.Option>
                        ))}
                    </Select>
                </div>

                <Table
                    bordered
                    loading={tableLoading}
                    empty={
                        <Empty
                            image={
                                <IllustrationNoContent style={{width: 150, height: 150}}/>
                            }
                            darkModeImage={
                                <IllustrationNoContentDark
                                    style={{width: 150, height: 150}}
                                />
                            }
                            description={'暂无内容，请添加'}
                            style={emptyStyle}
                        />
                    }
                    onRow={(record, index) => {
                        return {
                            onClick: (event) => {
                                this.setState({
                                    formData: record,
                                });
                            },
                        };
                    }}
                    dataSource={data}
                >
                    <Column title='id' dataIndex='id' key='id'/>
                    <Column title="视频名称" dataIndex="videoName" key="videoName"/>
                    <Column
                        title="视频分类"
                        dataIndex="category"
                        key="category"
                        render={(e) => {
                            return e.map((c: any, index: number) => {
                                return (
                                    <span key={index}>
                                        <Tag size='large' color="blue" type="light" style={{margin: '0 8px'}}>
                                            {' '}
                                            {videoTypeSelectData[c]}
                                            {' '}
                                        </Tag>
                                    </span>
                                );
                            });
                        }}
                    />
                    <Column
                        title="集数"
                        dataIndex="bluesNumber"
                        key="bluesNumber"
                    />
                    <Column
                        title="排序"
                        dataIndex="sort"
                        key="sort"
                        sorter={(a: { sort: number }, b: { sort: number }) =>
                            a.sort - b.sort > 0 ? 1 : -1
                        }
                    />
                    <Column
                        title="是否是电影"
                        dataIndex="isMovies"
                        key="isMovies"
                        render={(e) => {
                            return (
                                <>
                                    {
                                        e ? <Tag color='blue' type='solid'> 是 </Tag>
                                            : <Tag color='blue' type='light'> 不是 </Tag>
                                    }
                                </>
                            )
                        }}
                    />
                    <Column title="创建时间" dataIndex="create_time" key="create_time"/>
                    <Column title="更新时间" dataIndex="updated_time" key="updated_time"/>
                    <Column
                        title="操作"
                        render={() => (
                            <>
                                <ButtonGroup>
                                    <Tooltip content={'查看书签详情'}>
                                        <Button
                                            onClick={this.changeVideo}
                                            theme="light"
                                            type="secondary"
                                        >
                                            详情
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content={'编辑书签详情'}>
                                        <Button
                                            onClick={this.editVideo}
                                            theme="light"
                                            type="secondary"
                                        >
                                            编辑
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content={'添加视频分类'}>
                                        <Button
                                            onClick={this.changeTypeVisible}
                                            theme="light"
                                            type="secondary"
                                        >
                                            分类
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content={'视频子集管理'}>
                                        <Button
                                            onClick={this.goItemDetail}
                                            theme="light"
                                            type="secondary"
                                        >
                                            子集管理
                                        </Button>
                                    </Tooltip>
                                    <Popconfirm
                                        content="是否确认删除"
                                        onConfirm={() => this.delVideo()}
                                    >
                                        <span style={{display: 'inline-block'}}>
                                        <Tooltip content={'删除书签分类'}>
                                        <Button
                                            theme="light"
                                            type="danger"
                                            style={{marginRight: 8}}
                                        >
                                        删除
                                        </Button>
                                        </Tooltip>
                                        </span>
                                    </Popconfirm>
                                </ButtonGroup>
                            </>
                        )}
                    />
                </Table>
                <BookmarkSideSheet
                    visible={visible}
                    isCreate={isCreate}
                    initValues={initValues}
                    videoTypeSelect={videoTypeSelect}
                    submitForm={(values: any) => this.submitForm(values)}
                    getFormApi={(e: any) => this.getFormApi(e)}
                    change={this.changeSideSheet}
                />
                <VideoModal
                    modalVisible={modalVisible}
                    changeVideo={this.changeVideo}
                    formData={formData}
                />
                <TypeModal
                    getVideoList={this.getVideoList}
                    modalVisible={typeVisible}
                    changeVideo={this.changeTypeVisible}
                    formData={formData}
                    videoTypeSelect={videoTypeSelect}
                />
            </div>
        );
    }
}

const BookmarkSideSheet = (props: any) => {
    const style = {width: '100%'};
    const {
        isCreate,
        visible,
        change,
        getFormApi,
        initValues,
        videoTypeSelect,
        submitForm,
    } = props;

    const {Input, Select, TextArea, Switch} = Form;

    return (
        <>
            <SideSheet
                title={isCreate ? '创建书签' : '编辑书签'}
                visible={visible}
                onCancel={change}
            >
                <Form
                    getFormApi={getFormApi}
                    initValues={initValues}
                    style={{padding: 10, width: '100%'}}
                    onSubmit={(values) => submitForm(values)}
                >
                    <Input
                        field="videoName"
                        label="视频名称"
                        placeholder="请输入视频名称"
                        style={style}
                        trigger="blur"
                        rules={[{required: true, message: '书签名称不能为空'}]}
                    />
                    <Switch field='isMovies' label='是否是电影'/>
                    <Input
                        field="cover"
                        label="封面链接"
                        placeholder="请输入封面链接"
                        style={style}
                        trigger="blur"
                        rules={[{required: true, message: '书签链接不能为空'}]}
                    />
                    <Input
                        style={style}
                        field="bluesNumber"
                        label="集数"
                        placeholder="请填写集数"
                    />
                    <Input
                        style={style}
                        field="sort"
                        label="排序"
                        placeholder="请填写排序"
                    />
                    <Input
                        style={style}
                        field="shortDescribe"
                        label="视频简短描述"
                        placeholder="请填写视频简短描述"
                        rules={[{required: true, message: '视频简短描述不能为空'}]}
                    />
                    <TextArea
                        style={{...style, height: 120}}
                        field="describe"
                        label="视频描述"
                        placeholder="请填写视频描述"
                        rules={[{required: true, message: '视频描述不能为空'}]}
                    />
                    <div style={{display: 'flex', justifyContent: 'flex-end'}}>
                        <Button style={{marginRight: 8}} htmlType="reset">
                            重 置
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            className="btn-margin-right"
                        >
                            提 交
                        </Button>
                    </div>
                </Form>
            </SideSheet>
        </>
    );
};

const VideoModal = (props: any) => {
    const {modalVisible, changeVideo, formData} = props;
    return (
        <Modal
            title={formData.videoName}
            visible={modalVisible}
            onOk={changeVideo}
            onCancel={changeVideo}
            className="modalStyle"
            centered
            bodyStyle={{paddingTop: '20px'}}>
            <div>
                视频描述：{formData.shortDescribe}
            </div>
            <div>
                视频描述：{formData.describe}
            </div>
        </Modal>
    );
};

const TypeModal = (props: any) => {
    const {modalVisible, changeVideo, formData, videoTypeSelect, getVideoList} = props;
    let category = formData.category
    let options: any = [];
    videoTypeSelect.forEach((t: any) => {
        options.push({label: t.name, value: t.id * 1},)
    })
    const onChange = async (e: any) => {
        const newArr = getArrDifference(e, category)
        let res: any = {}
        if (e.length > category.length) {
            res = await videoAPI.addVideoCategory({
                videoId: formData.id,
                categoryId: newArr[0]
            })

        } else {
            res = await videoAPI.deleteCategory({
                videoId: formData.id,
                categoryId: newArr[0]
            })
        }
        if (res.status) {
            getVideoList()
            changeVideo()
            Toast.success({
                content: `修改视频分类成功！`,
                duration: 3,
            });
        } else {
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }
    const getArrDifference = (arr1: any, arr2: any) => {
        return arr1.concat(arr2).filter((v: any, i: any, arr: string | any[]) => {
            return arr.indexOf(v) === arr.lastIndexOf(v);
        })
    };
    return (
        <Modal
            title={formData.videoName}
            visible={modalVisible}
            onOk={changeVideo}
            onCancel={changeVideo}
            className="modalStyle"
            centered
            footer={
                <Button type="primary" onClick={changeVideo}>
                    取消
                </Button>
            }
            bodyStyle={{paddingTop: '20px'}}>
            <CheckboxGroup value={category}
                           onChange={onChange} options={options} direction='horizontal'/>
        </Modal>
    );
};
